using System;
using System.Data.Common;
using uk.co.tonyditchfield.utility.logging;

namespace uk.co.tonyditchfield.tort.database.providers
{
    /// <summary>
    /// Generic Connection provider for all engines
    /// </summary>
    internal static class BaseClient
    {
        private static ILog logger = new Log();
        /// <summary>
        /// The connection for all database usage.
        /// </summary>
        /// <param name="typeOfConnection"></param>
        /// <returns>DbConnection of base type associated with engine</returns>
        /// <exception cref="PersistenceException">Thrown when a connection failure occurs</exception>
        internal static DbConnection Connection(Type typeOfConnection)
        {
            try
            {
                DbConnection connection = (DbConnection)Activator.CreateInstance(typeOfConnection, ConnectionAttributes.ServerDetails().Connection);
                // Check and set the connection details on the first connection only.
                if (ServerDetails.ServerVersion == null)
                {
                    connection.Open();
                    ServerDetails.ServerVersion = connection.ServerVersion;
                    connection.Close();
                    logger.LogInfo("Server Version: " + ServerDetails.ServerVersion);
                }
                return connection;
            }
            catch (DbException dbe)
            {
                logger.LogError(dbe);
                throw new exception.PersistenceException(dbe.ErrorCode, dbe.InnerException);
            }
        }
    }
}
